//
//  HFAddAddressViewController.m
//  APPStart
//
//  Created by 慧鼎科技 on 2018/11/10.
//  Copyright © 2018 WQ. All rights reserved.
//

#import "HFAddAddressViewController.h"
#import "DISgoodsDetailViewController.h"

#import "HFTiXianTFCell.h"


#import "HFDefaultAddressCell.h"
//#import "WqGaoDeLocationViewController.h"

#import "BaseNavViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "MBProgressHUD.h"
#import "WQTableViewCell.h"
#import "MOFSPickerManager.h"

@interface HFAddAddressViewController () <UITableViewDelegate, UITableViewDataSource>
{
    NSString *_name;
    NSString *_mobile;
    NSString *_area;
    NSString *_address;
    NSInteger _isDefault;
    NSString *_WQaddress;
    NSString *shengshiqu;

}
@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSArray *titleArray;

@property (nonatomic, strong) NSArray *placeholderArray;

@property (nonatomic, strong) NSArray *contentArray;

@property (nonatomic, strong) NSString *editstr;

@end

@implementation HFAddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.leftbutton setImage:imgname(@"left_icon") forState:(UIControlStateNormal)];

    _titleArray = @[ @"所在地区", @"详细地址"];
//    _placeholderArray = @[@"输入姓名", @"输入电话", @"输入所在地区(如河南省郑州市金水区)", @"输入详细地址"];
    _placeholderArray = @[ @"选择所在地区", @"输入详细地址"];

    [self configNavi];
    
    [self.view addSubview:self.tableView];
    
    [self configSubmitBtn];
    
}


- (void)configNavi {
    if (self.model) {
        self.title = @"编辑";
        _area = _model.areaAdd;
        _address = _model.address;
        _contentArray = @[ _model.areaAdd, _address];
        shengshiqu = [NSString stringWithFormat:@"%@-%@-%@",_model.province,_model.city,_model.area];
        
        self.editstr =_model.area;
    } else {
        self.title = @"添加地址";
        _contentArray = @[@"", @"", @"", @""];
    }
}

- (void)configSubmitBtn {
    UIButton *btn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    btn.frame = CGRectMake(30, ScreenH-150, ScreenW-60, 48);
    [btn setTitle:@"确认" forState:(UIControlStateNormal)];
    [btn setBackgroundColor:[UIColor colorWithHexString:@"#70BE68"]];
    btn.titleLabel.textColor = [UIColor colorWithHexString:@"ffffff"];
    btn.titleLabel.font = [UIFont systemFontOfSize:15];
    [self.view addSubview:btn];
    btn.layer.masksToBounds = YES;
    btn.layer.cornerRadius = 4;
    [btn addTarget:self action:@selector(submitBtnClick:) forControlEvents:(UIControlEventTouchUpInside)];
}


- (void)requestAddAddressData {
    
    if ( strIsEmpty(shengshiqu) || strIsEmpty(_address)) {
        ShowToastWithText(@"请填写全部信息");
        return;
    }

    
//http://192.168.2.114:8096/repAddress/Addaddress?address={"area":"110101","address":"address","province":"110000","city":"110100","is_default":"1"}

//    NSDictionary *dic = @{
//                          @"consignee":safe(_name),
//                          @"mobile":safe(_mobile),
//                          @"region_name":safe(_area),
//                          @"building_name":safe(_address),
//                          @"is_default":@(_isDefault)
//                          };
    NSArray  *array = [shengshiqu componentsSeparatedByString:@"-"];
    
 

    NSDictionary *dic = @{
                          @"area":array[2],
                          @"address":safe(_address),
                          @"province":array[0],
                          @"city":array[1]
                          };
    
    kWeakSelf;
//    NSString *json = [HFTools toJSONString:dic];
//    NSMutableDictionary *mudci = @{@"address":json};
//
    [NetWorkTool POST:changeInfo param:[dic mutableCopy] success:^(id dic) {
        NSLog(@"%@", dic);
        
//        if (self.myBlock) {
//            self.myBlock(@"");
//            for (UIViewController *controller in self.navigationController.viewControllers) {
//
//                if ([controller isKindOfClass:[DISgoodsDetailViewController class]]) {
//                    DISgoodsDetailViewController *vc =(DISgoodsDetailViewController *)controller;
//                    [self.navigationController popToViewController:vc animated:YES];
//                }
//            }
//            return ;
//
//
//        }
        
            
        if (self.myBlock) {
            self.myBlock(@"");
        }
        
        [weakSelf leftClick];
        
    } other:^(id dic) {
        ShowToastWithText(dic[@"msg"]);
    } fail:^(NSError *error) {
        
    } needUser:YES];
    
}


#pragma mark -- click点击事件
- (void)submitBtnClick:(UIButton *)sender {
    
    NSLog(@"提交");

        [self requestAddAddressData];
    
}


#pragma mark -- tableView代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _titleArray.count ;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    if (indexPath.row < _titleArray.count) {
        HFTiXianTFCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HFTiXianTFCell" forIndexPath:indexPath];
        if (indexPath.row ==0 ) {
            cell.contentTF.tag = 777;
            cell.contentTF.userInteractionEnabled = NO;
            cell.selebut.hidden = NO;
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell configDataWithTitle:[_titleArray safeObjectAtIndex:indexPath.row] placeHolder:[_placeholderArray safeObjectAtIndex:indexPath.row] content:[_contentArray safeObjectAtIndex:indexPath.row]];
        if (indexPath.row ==0 ) {

            if (!strIsEmpty(_WQaddress)) {
                cell.contentTF.text = _WQaddress;
                self->_area = _WQaddress;

            }
        }
        
        cell.inputContentBlock = ^(NSString * _Nonnull content) {
            switch (indexPath.row) {
                case 0:

                    [self locationAction];
                    break;
                case 1:
                    self->_address = content;
                    break;
                case 2:
//                    self->_area = content;
                    [self locationAction];
                    break;
                case 3:
                    self->_address = content;
                    break;
                default:
                    break;
            }
        };
        
        return cell;
//    } else {
//        HFDefaultAddressCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HFDefaultAddressCell" forIndexPath:indexPath];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        if (_model) {
//            cell.selectBtn.selected = _model.is_default==1 ? YES : NO;
//        }
//        return cell;
//    }
    
}
#pragma mark -- 定位服务
-(void)locationAction{
    
    


    kWeakSelf;
    [[MOFSPickerManager shareManger] showMOFSAddressPickerWithDefaultZipcode:@"410000-410100-410184" title:@"选择地址" cancelTitle:@"取消" commitTitle:@"确定" commitBlock:^(NSString * _Nullable address, NSString * _Nullable zipcode) {

        
        self->_WQaddress = address;
        [weakSelf.tableView reloadData];
        NSLog(@"%@", zipcode);
        self->shengshiqu = zipcode;
    } cancelBlock:^{
        
    }];
//    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];

    
    /*
    KMyLog(@"定位");
    kWeakSelf;
    if ([self isLocationServiceOpen]) {
        WqGaoDeLocationViewController *locaVC = [[WqGaoDeLocationViewController alloc]init];
        BaseNavViewController * navigation = [[BaseNavViewController alloc]initWithRootViewController:locaVC];
        [self presentViewController:navigation animated:YES completion:nil];
        locaVC.locaBlock = ^(NSMutableDictionary *locadic) {
            NSLog(@"%@", locadic);
            _WQaddress = [NSString stringWithFormat:@"%@",[locadic objectForKey:@"building_name"]];
            [weakSelf.tableView reloadData];
             NSString *info = [NSString stringWithFormat:@"{\"text\":\"%@\",\"location\":\"%@,%@\"}", locadic[@"building_name"], locadic[@"longitude"], locadic[@"latitude"]];
            
            NSString *callBack = [NSString stringWithFormat:@"getLocationCallBack('%@')", info];
            
        };
    }else{
        //未开启定位权限
        UIAlertController *alertCon = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"需要您开启定位权限,是否允许" preferredStyle:UIAlertControllerStyleAlert];
        
        [alertCon addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            KMyLog(@"取消");
        }]];
        [alertCon addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            KMyLog(@"确定");
            if ([[[UIDevice currentDevice] systemVersion] integerValue] >9.9) {
                
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                
            } else {
                
                NSURL *url = [NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"];
                
                [[UIApplication sharedApplication] openURL:url];
            }
            
        }]];
        
        
    }
   */
}

//是否开启定位
- (BOOL)isLocationServiceOpen {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        return NO;
    } else
        return YES;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _titleArray.count) {
        HFDefaultAddressCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        cell.selectBtn.selected = !cell.selectBtn.selected;
        _isDefault = cell.selectBtn.selected?1:0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == _titleArray.count) {
        return 54;
    }
    return 49;
}

#pragma mark -- 懒加载
- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNaviHeight, ScreenW, ScreenH-kNaviHeight) style:(UITableViewStylePlain)];
        _tableView.backgroundColor = [UIColor colorWithHexString:@"eeeeee"];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.contentInset = UIEdgeInsetsMake(0, 0, 40, 0);
        if (iOS11) {
            self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView.tableFooterView = [UIView new];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 48;
        [_tableView registerNib:[UINib nibWithNibName:@"HFTiXianTFCell" bundle:nil] forCellReuseIdentifier:@"HFTiXianTFCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"HFDefaultAddressCell" bundle:nil] forCellReuseIdentifier:@"HFDefaultAddressCell"];
             [_tableView registerNib:[UINib nibWithNibName:@"WQTableViewCell" bundle:nil] forCellReuseIdentifier:@"WQTableViewCell"];
        
        
    }
    return _tableView;
}
- (BOOL)isMobileNumberOnly:(NSString *)mobileNum
{
    
    NSString * MOBILE = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    if ([regextestmobile evaluateWithObject:mobileNum] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}
@end
